<?php
Yii::import('application.modules.menu.utililies.menuService');

class RecipiedetailController extends ControllerBase
{
	public function init() {
            parent::init();
            $this->defaultAction = 'admin';
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Recipiedetail;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Recipiedetail']))
		{
                    $model->attributes = $_POST['Recipiedetail'];          //materialid     
                    foreach ($_POST['Material'] as $m => $value) {
                        foreach ($value as $k => $v) {
                            $quantity = preg_replace('/\\s/', '', $v);
                            if (intval($quantity) != 0) {
                                //insert into material request detail
                                $model = new Recipiedetail;
                                $model->recipieid = $_POST['Recipiedetail']['materialid']; //column recipieid in recipiedetail named materialid in create form
                                $model->materialquantity = $quantity;
                                $model->materialid = $k;
                                $model->save();
                            }
                        }
                    }
                    
                    //add syrup
                    foreach ($_POST['Syrup'] as $s => $value) {
                        foreach ($value as $k => $v) {
                            $quantity = preg_replace('/\\s/', '', $v);
                            if (intval($quantity) != 0) {
                                //insert into syrup request detail
                                $model = new Recipiedetail;
                                $model->recipieid = $_POST['Recipiedetail']['materialid']; //column recipieid in recipiedetail named syrupid in create form
                                $model->syrupquantity = $quantity;
                                $model->syrupid = $k;
                                $model->materialid = null;
                                $model->save();
                            }
                        }
                    }
                    
                    $this->setMessage('Create Recipe Successful');
                    $this->refresh();
		}
                
                $materialList = Material::model()->findAll();
                $syrupList = Syrup::model()->findAll();

                $this->render('create',array(
                    'model'=>$model,
                    'materialList' => $materialList,
                    'syrupList' => $syrupList
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
                $model= Recipiedetail::model()->find(array(
                    'condition' => 'recipieid = :id',
                    'params' => array(
                        ':id' => $id,
                    )
                ));

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

                if(isset($_POST['Recipiedetail']))
		{                    
                    $model->attributes=$_POST['Recipiedetail'];          //materialid   
                    //add or update material
                    foreach ($_POST['Material'] as $m => $value){
                        foreach ($value as $k => $v){
                            $quantity = preg_replace('/\\s/', '', $v);                                
                            if (intval($quantity) != 0){
                                $recipieDetailModel = Recipiedetail::model()->find(array(
                                    'condition' => 'recipieid = :id AND materialid = :materialid',
                                    'params' => array(
                                        ':id' => $_POST['Recipiedetail']['materialid'],
                                        ':materialid' => $k,
                                    )
                                ));
                                //update recipie materials
                                if($recipieDetailModel !== null){
                                    $recipieDetailModel->updateAll(
                                        array(
                                            'materialquantity' => $quantity,
                                            'materialid' => $k
                                        ),
                                        'recipieid = ' . $_POST['Recipiedetail']['materialid'] . ' AND materialid = ' . $k);

                                }else{  //insert new recipie material
                                  $recipieDetailModel = new Recipiedetail;
                                  $recipieDetailModel->materialid = $k;
                                  $recipieDetailModel->materialquantity = $quantity;
                                  $recipieDetailModel->recipieid = $id;
                                  $recipieDetailModel->save();
                                }                                    
                            }
                        }
                    }

                    //add or update syrup
                    foreach ($_POST['Syrup'] as $s => $value){
                        foreach ($value as $k => $v){             
                            $quantity = preg_replace('/\\s/', '', $v);
                            if (intval($quantity) != 0){
                                $recipieDetailModel = Recipiedetail::model()->find(array(
                                        'condition' => 'recipieid = :id AND syrupid = :syrupid',
                                        'params' => array(
                                            ':id' => $_POST['Recipiedetail']['materialid'],
                                            ':syrupid' => $k,
                                        )
                                ));  
                            }
                            
                            //update recipie syrup
                            if($recipieDetailModel !== null){
                                $a = $recipieDetailModel->updateAll(
                                    array(
                                        'syrupquantity' => $quantity,
                                        'syrupid' => $k
                                    ),
                                    'recipieid = ' . $_POST['Recipiedetail']['materialid'] . ' AND syrupid = ' . $k);

                            } else{  //insert new recipie material
                                  $recipieDetailModel = new Recipiedetail;
                                  $recipieDetailModel->syrupid = $k;
                                  $recipieDetailModel->syrupquantity = $quantity;
                                  $recipieDetailModel->recipieid = $id;
                                  $recipieDetailModel->save();
                            }     
                        }                        
                    }
                    
                    $this->setMessage('Update Recipe Successful');
		}

                //load material in recipie
                $presetRecipie = Recipiedetail::model()->findAll(array(
                    'condition' => 'recipieid = :id',
                    'params' => array(
                        ':id' => $id,
                    )
                ));
                
                //load active key of recipie
                $active = Recipie::model()->find(array(
                    'condition' => 'recipieid = :id',
                    'params' => array(
                        ':id' => $id,
                    )
                ));
                
                $materialList = Material::model()->findAll();
                $syrupList = Syrup::model()->findAll();
		$this->render('update',array(
                    'model'=>$model,
                    'materialList' => $materialList,
                    'presetRecipie' => $presetRecipie,
                    'active' => $active->active,
                    'syrupList' => $syrupList
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
//			$this->loadModel($id)->delete();
                        $recipie = Recipie::model()->find(array(
                            'condition' => 'recipieid = :id',
                            'params' => array(
                                ':id' => $id,
                            )
                        ));
                        $recipie->active = 0;
                        $recipie->update('active');

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Recipiedetail');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Recipiedetail('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Recipiedetail']))
			$model->attributes=$_GET['Recipiedetail'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Recipiedetail::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='Recipiedetail-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
    public function beforeAction($action) {
        parent::beforeAction($action);
        if (Yii::app()->user->id === null)
            $this->redirect(Yii::app()->createUrl('site/login'));
        return true;
        $this->redirect(Yii::app()->createUrl('site/login'));
    }
}
